﻿using DoNet.Token;
using DoNet.Token.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace DoNet.TokenWeb.Controllers
{
    [ApiController]
    //[Route("api/[controller]")]
    [Route("api/token")]
    [Authorize]
    public class TokenController : ControllerBase
    {
        private readonly IConfiguration _config;
        private readonly int accessExpire = 0;
        private readonly int refreshExpire = 0;

        public TokenController(IConfiguration config)
        {
            _config = config;
            accessExpire = Convert.ToInt32(_config["TokenSettings:AccessExpire"] ?? "0");
            refreshExpire = Convert.ToInt32(_config["TokenSettings:RefreshExpire"] ?? "0");
        }

        [HttpGet("get")]
        public ApiResult GetToken(string appId, string appSecret)
        {
            var claims = new Dictionary<string, string>
            {
                { "uid", "1001" },
                { "role", "Admin" }
            };

            var model = AppService.GetAppByAppId(appId);
            if (model != null)
            {
                if (appSecret == model.AppSecret)
                {
                    var token = CustomTokenService.GetTokenPair(appId, appSecret, accessExpire, refreshExpire, claims);
                    return ApiResultHelper.Success(token);
                }
                else
                {
                    return ApiResultHelper.Error("AppSecret不正确！");
                }
            }
            else
            {
                return ApiResultHelper.Error("AppId不正确！");
            }
        }

        [HttpGet("verify")]
        public ApiResult Verify(string accessToken)
        {
            var isVerify = CustomTokenService.ValidateToken(accessToken);
            if (isVerify)
            {
                return ApiResultHelper.Success(CustomTokenService.ParseClaims(accessToken));
            }
            else
            {
                return ApiResultHelper.Error("无效的令牌");
            }
        }

        [HttpGet("refresh")]
        public ApiResult Refresh(string refreshToken)
        {
            if (CustomTokenService.ValidateToken(refreshToken))
            {
                var result = CustomTokenService.ForceRefresh(refreshToken, accessExpire);
                if (result != null)
                {
                    return ApiResultHelper.Success(result);
                }
            }
            return ApiResultHelper.Error("无效的刷新令牌");
        }

        //比如退出登录时 吊销所有Token
    }
}
